package ru.arriah.servicedesk.help;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import ru.arriah.common.bean.PagingLinkBean;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.UtilityManagerLocalHome;

public final class Utils implements ComponentsNames {      
   
   public static String randomNumeric(int count) {
      return random(count, false, true);
   }

   
   public static String randomAlphanumeric(int count) {
      return random(count, true, true);
   }

   
   public static String randomAlphabetic(int count) {
      return random(count, true, false);
   }     
   
   
   private static String random(
      int count,
      boolean letters, 
      boolean numbers 
   ) {
      int end = 'z' + 1;
      int start = ' ';

      Random random = new Random();
      
      if (count == 0) {
         return "";
      } else if (count < 0) {
         throw new IllegalArgumentException(
            "Requested random string length " + count + " is less than 0."
         );
      }
      
      if (!letters && !numbers) {
         start = 0;
         end = Integer.MAX_VALUE;
      }

      StringBuffer buffer = new StringBuffer();
      
      int gap = end - start;

      while (count-- != 0) {
         char ch;         
         ch = (char) (random.nextInt(gap) + start);
                  
         if ((letters && numbers && Character.isLetterOrDigit(ch)) || (letters && Character.isLetter(ch)) || (numbers && Character.isDigit(ch)) || (!letters && !numbers)) {
            buffer.append(ch);
         } else {
            count++;
         }
      }
      return buffer.toString();
   }
   
   
   public static String getUserRole(HttpServletRequest request) {
      return (String)request.getSession().getAttribute("role");
   }
   
   
   public static String getControllerAlias(HttpServletRequest request) {
      return (String)request.getSession().getAttribute("alias");
   }
   
   
   public static long parseLongQuietly(String value) {
      try {
         return Long.parseLong(value);
      } catch (NumberFormatException e) {
         System.out.println("Exception: " + value + "is not a number");
         return 0;
      }
   }
   
   /**
    * @author Mixa
    * @param fstDate
    * @param sndDate
    * @return 
    */
    public static boolean isSameDay(Date fstDate, Date sndDate) {
      Calendar fst = new GregorianCalendar();
      Calendar snd = new GregorianCalendar();
      
      fst.setTime(fstDate);
      snd.setTime(sndDate);
      
      return fst.get(Calendar.YEAR) == snd.get(Calendar.YEAR) &&
             fst.get(Calendar.DAY_OF_YEAR) == snd.get(Calendar.DAY_OF_YEAR) ? 
             true : false;
   }
   
   
   /**
    * Return user id from session attribute userId
    * @param HttpServletRequest request
    * @return int userId
    */
   public static Integer getUserId(HttpServletRequest request) {
      return (Integer)request.getSession().getAttribute("userId");
   }
   
   
   public static RequestManagerLocalHome getRequestManagerHomeInterface() 
   throws NamingException {
      return (RequestManagerLocalHome) (new InitialContext()).lookup(
         JNDI_NAME_REQUESTMANAGER
      );
   }
   
   
   public static OrganizationManagerLocalHome getOrganizationManagerHomeInterface()
      throws NamingException {
      return (OrganizationManagerLocalHome) (new InitialContext()).lookup(
         JNDI_NAME_ORGANIZATIONMANAGER
      );
   }

   
   public static ClientManagerLocalHome getClientManagerHomeInterface()
      throws NamingException {
      return (ClientManagerLocalHome) (new InitialContext()).lookup(
         JNDI_NAME_CLIENTMANAGER
      );
   }
   
   
   public static GroupManagerLocalHome getGroupManagerHomeInterface()
      throws NamingException {
      return (GroupManagerLocalHome) (new InitialContext()).lookup(
         JNDI_NAME_GROUPMANAGER
      );
   }
   
   
   public static UtilityManagerLocalHome getUtilityManagerHomeInterface()
   throws NamingException {
      return (UtilityManagerLocalHome) (new InitialContext()).lookup(
         JNDI_NAME_UTILITYMANAGER
      );
   }
   
   
   public static EmployeeManagerLocalHome getEmployeeManagerHomeInterface()
   throws NamingException {
      return (EmployeeManagerLocalHome) (new InitialContext()).lookup(
         JNDI_NAME_EMPLOYEEMANAGER
      );
   }
   
   
   public static DataSource getDataSource()
      throws RemoteException, NamingException {     
      return (DataSource) (new InitialContext()).lookup(
          JDBC_NAME
      );
   }
   
   
   public static int idVal(String strVal) {
      try {
         return Integer.parseInt(strVal);     
      } catch (Exception e) {
         return 0;
      }
   }
   
   
   public static void pageNavigationToRequest(
      int currentPage, 
      Integer totalItems,
      String url, 
      HttpServletRequest request
   ) {
      pageNavigationToRequest(
         currentPage, 
         totalItems,
         url, 
         request,
         "listRequests",
         "currentPage"
      );
   }
   
   
   public static void pageNavigationToRequest(
      int currentPage, 
      Integer totalItems,
      String url, 
      HttpServletRequest request,
      String listName,
      String attrCPName
    ) {
     ArrayList<PagingLinkBean> pagingLinks = 
        new ArrayList<PagingLinkBean>();

     //int itemsPerPage = Integer.parseInt(config.getProperty("ITEMS_PER_PAGE"));
     int itemsPerPage = 5;

     int sstart = 0;
     int send = 0;
     int add = 0;

     if (totalItems < itemsPerPage)
       return;

     if (currentPage != 0) {
       pagingLinks.add(new PagingLinkBean(url + "0", "&lt;&lt"));
       pagingLinks.add(new PagingLinkBean(url + (currentPage - 1), "&lt;"));
     } else {
       pagingLinks.add(new PagingLinkBean("", "&lt;&lt"));
       pagingLinks.add(new PagingLinkBean("", "&lt;"));
     }

     sstart = currentPage - 2;
     send = currentPage + 2;

     if (totalItems % itemsPerPage == 0)
       add = 0;
     else
       add = 1;

     if (send * itemsPerPage > totalItems)
       send = Math.round(totalItems / itemsPerPage) + add;
     if (sstart < 0)
       sstart = 0;

     for (int i = sstart; i < send; i++) {
       if (i == currentPage)
         pagingLinks.add(new PagingLinkBean("", (i + 1) + "/"
             + (Math.round(totalItems / itemsPerPage) + add)));
       else
         pagingLinks.add(new PagingLinkBean(url + i, (i + 1) + ""));
     }

     if (currentPage + (1 - add) < Math.round(totalItems / itemsPerPage)) {
       pagingLinks.add(new PagingLinkBean(url + (currentPage + 1), "&gt;"));
       pagingLinks.add(new PagingLinkBean(url
           + (Math.round(totalItems / itemsPerPage) - (1 - add)), "&gt;&gt;"));
     } else {
       pagingLinks.add(new PagingLinkBean("", "&gt;"));
       pagingLinks.add(new PagingLinkBean("", "&gt;&gt;"));
     }

     request.setAttribute(listName, pagingLinks);
     request.setAttribute(attrCPName, currentPage);
   }
}
